
/*
 * Hlpay-Plus aggregate payment system. Copyright
 * (c) 2022-2023 Hlpay Team Copyright has the right of final interpretation.
 */

package com.hlkj.pay.controller.admin;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.hlkj.framework.common.pojo.CommonResult;
import com.hlkj.framework.common.pojo.LocalContext;
import com.hlkj.framework.common.pojo.PageResult;
import com.hlkj.framework.common.provider.Aes256EncryptionProvider;
import com.hlkj.framework.common.util.collection.CollectionUtils;
import com.hlkj.pay.app.adminuser.IAdminUserAppService;
import com.hlkj.pay.app.adminuser.IRoleAppService;
import com.hlkj.pay.app.adminuser.IUserPermissionAppService;
import com.hlkj.pay.app.merchant.IMerchantInfoAppService;
import com.hlkj.pay.app.transfer.UserDoToResp;
import com.hlkj.pay.controller.BaseController;
import com.hlkj.pay.dto.LocalAdminUserRequest;
import com.hlkj.pay.dto.admin.AdminUserDto;
import com.hlkj.pay.dto.admin.AdminUserQueryDto;
import com.hlkj.pay.dto.admin.OrganizationQueryDto;
import com.hlkj.pay.infrastructure.model.admin.AdminUserRoleMappingDO;
import com.hlkj.pay.infrastructure.model.admin.OrganizationDO;
import com.hlkj.pay.service.admin.IAdminUserService;
import com.hlkj.pay.service.admin.IOrganizationService;
import com.hlkj.pay.vo.admin.req.user.*;
import com.hlkj.pay.vo.admin.resp.user.AdminUserDetailResp;
import com.hlkj.pay.vo.admin.resp.user.AdminUserPermissionResp;
import com.hlkj.pay.vo.admin.resp.user.AdminUserResp;
import com.hlkj.pay.vo.common.req.DeleteIdReq;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author HlpayTeam
 * @date 2024/09/03 14:10
 */
@Tag(name = "用户配置")
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/v1/adminuser/user")
public class AdminUserController extends BaseController {

    private final IAdminUserAppService userAppService;

    private final IRoleAppService roleAppService;

    private final IAdminUserService userService;

    private final Aes256EncryptionProvider aes256EncryptionProvider;

    private final IUserPermissionAppService userPermissionAppService;

    private final IOrganizationService organizationService;

    private final IMerchantInfoAppService merchantInfoAppService;

    @Operation(summary = "用户分页列表")
    @GetMapping("/page")
    public CommonResult<PageResult<AdminUserResp>> queryUserPage(AdminUserPageQueryReq adminUserPageQueryReq) {
        AdminUserQueryDto adminUserQueryDto = BeanUtil.copyProperties(adminUserPageQueryReq, AdminUserQueryDto.class);
        // 获取当前用户角色
        LocalAdminUserRequest localAdminUserRequest = (LocalAdminUserRequest) LocalContext.get();

        boolean isAdmin = false;
        List<AdminUserRoleMappingDO> roleMappingDOList = userService.queryUserRoles(localAdminUserRequest.getUserId());
        if(CollUtil.isNotEmpty(roleMappingDOList)){
            List<String> roles = roleMappingDOList.stream().map(AdminUserRoleMappingDO::getRoleCode).collect(Collectors.toList());
            if(CollUtil.isNotEmpty(roles)){
                // 判断是否含有管理员权限
                isAdmin = roleAppService.isAdmin(roles,adminUserPageQueryReq.getSysType());
                if(!isAdmin){
                    adminUserQueryDto.setRoleCodes(roles);
                }
            }
        }

        PageResult<AdminUserDto> userPageResult = userService.queryUserPage(adminUserQueryDto);
        List<AdminUserDto> list = userPageResult.getList();
        if (CollectionUtils.isEmpty(list)) {
            return buildPageResult(userPageResult, Collections.emptyList());
        }
        List<String> partCodes = new ArrayList<>();
        list.stream().forEach(adminUserDto -> {
            try {
                adminUserDto.setPhone(aes256EncryptionProvider.decryptString(adminUserDto.getPhoneEncrypt()));
            }
            catch (Exception e) {
                adminUserDto.setPhone(adminUserDto.getPhoneEncrypt());
            }
            try {
                adminUserDto.setEmail(aes256EncryptionProvider.decryptString(adminUserDto.getEmailEncrypt()));
            }
            catch (Exception e) {
                adminUserDto.setEmail(adminUserDto.getEmailEncrypt());
            }
            if (!CollectionUtils.isEmpty(adminUserDto.getPartCodes())) {
                partCodes.addAll(adminUserDto.getPartCodes());
            }
        });
        OrganizationQueryDto organizationQueryDto = new OrganizationQueryDto();
        organizationQueryDto.setOrganizationCodes(partCodes);
        List<OrganizationDO> organizationDOList = organizationService.queryOrganizationList(organizationQueryDto);
        Map<String, OrganizationDO> organizationDOMap = new HashMap<>();
        if (!CollectionUtils.isEmpty(organizationDOList)) {
            organizationDOMap = organizationDOList.stream().collect(Collectors.toMap(organizationDO -> organizationDO.getOrganizationCode(), Function.identity(), (t1, t2) -> t1));
        }
        Map<String, OrganizationDO> finalOrganizationDOMap = organizationDOMap;
        list.stream().forEach(adminUserDto -> {
            if (!CollectionUtils.isEmpty(adminUserDto.getPartCodes())) {
                adminUserDto.setPartNames(new ArrayList<>());
                adminUserDto.getPartCodes().stream().forEach(partCode -> {
                    OrganizationDO organizationDO = finalOrganizationDOMap.get(partCode);
                    if (organizationDO != null) {
                        adminUserDto.getPartNames().add(organizationDO.getOrganizationName());
                    }
                });
            }
        });

        List<AdminUserResp> adminUserResps = UserDoToResp.INSTANCE.domainToRespList(list);
        processMerchantList(adminUserResps);
        return buildPageResult(userPageResult, adminUserResps);
    }

    @Operation(summary = "用户不分页列表")
    @GetMapping("")
    public CommonResult<List<AdminUserResp>> queryUserList(AdminUserPageQueryReq adminUserPageQueryReq) {
        AdminUserQueryDto adminUserQueryDto = BeanUtil.copyProperties(adminUserPageQueryReq, AdminUserQueryDto.class);
        List<AdminUserDto> list = userService.queryUserList(adminUserQueryDto);
        if (CollectionUtils.isEmpty(list)) {
            return CommonResult.success(Collections.emptyList());
        }
        list.stream().forEach(adminUserDto -> {
            try {
                adminUserDto.setPhone(aes256EncryptionProvider.decryptString(adminUserDto.getPhoneEncrypt()));
            }
            catch (Exception e) {
                adminUserDto.setPhone(adminUserDto.getPhoneEncrypt());
            }
            try {
                adminUserDto.setEmail(aes256EncryptionProvider.decryptString(adminUserDto.getEmailEncrypt()));
            }
            catch (Exception e) {
                adminUserDto.setEmail(adminUserDto.getEmailEncrypt());
            }
        });
        List<AdminUserResp> adminUserResps = UserDoToResp.INSTANCE.domainToRespList(list);
        return CommonResult.success(adminUserResps);
    }

    @Operation(summary = "用户详情")
    @GetMapping("/detail")
    CommonResult<AdminUserDetailResp> queryUserDetail(@RequestParam(required = false, name = "userId") Long userId) {
        return userAppService.userDetail(userId);
    }

    @Operation(summary = "新增用户")
    @PostMapping("")
    CommonResult<Long> addUser(@Validated @RequestBody AdminUserAddReq adminUserAddReq) {
        return userAppService.addUser(adminUserAddReq);
    }

    @Operation(summary = "更新用户")
    @PutMapping("")
    CommonResult<Void> updateUser(@Validated @RequestBody AdminUserUpdateReq adminUserUpdateReq) {
        return userAppService.updateUser(adminUserUpdateReq);
    }

    @Operation(summary = "更新用户手机号")
    @PutMapping("/updatePhone")
    CommonResult<Void> updatePhone(@Validated @RequestBody AdminUserPhoneUpdateReq adminUserPhoneUpdateReq) {
        return userAppService.updatePhone(adminUserPhoneUpdateReq);
    }

    @Operation(summary = "删除用户")
    @DeleteMapping("")
    CommonResult<Void> deleteUser(@RequestBody DeleteIdReq deleteIdReq) {
        return userAppService.deleteUser(deleteIdReq.getId());
    }

    @Operation(summary = "更新用户对应的角色")
    @PostMapping("/role")
    CommonResult<Void> assignUserRole(@Validated @RequestBody AdminUserAddRoleReq adminUserAddRoleReq) {
        return userAppService.assignUserRole(adminUserAddRoleReq);
    }

    @Operation(summary = "更新用户密码")
    @PostMapping("/updatePwd")
    CommonResult<Void> updatePwd(@Validated @RequestBody AdminUserUpdatePwdReq adminUserUpdatePwdReq) {
        return userAppService.updatePwd(adminUserUpdatePwdReq);
    }

    @Operation(summary = "更新交易密码")
    @PostMapping("/updateTranPwd")
    CommonResult<Void> updateTransactionPwd(@Validated @RequestBody AdminUserUpdateTranPwdReq adminUserUpdateTranPwdReq) {
        return merchantInfoAppService.updateTranPwd(adminUserUpdateTranPwdReq);
    }

    @Operation(summary = "找回交易密码")
    @PostMapping("/callTranPwd")
    CommonResult<Void> callTransactionPwd(@Validated @RequestBody AdminUserCallTranPwdReq adminUserCallTranPwdReq) {
        return merchantInfoAppService.callTranPwd(adminUserCallTranPwdReq);
    }

    @Operation(summary = "重置密码")
    @PostMapping("/resetPwd")
    CommonResult<String> resetPwd(@RequestBody DeleteIdReq deleteIdReq) {
        return userAppService.resetPwd(deleteIdReq.getId());
    }

    @Operation(summary = "更新用户状态")
    @PostMapping("/updateStatus")
    CommonResult<Void> updateStatus(@Validated @RequestBody AdminUserUpdateStatusReq adminUserUpdateStatusReq) {
        return userAppService.updateStatus(adminUserUpdateStatusReq);
    }

    @Operation(summary = "用户权限列表")
    @GetMapping("/permission")
    CommonResult<AdminUserPermissionResp> permission(@RequestParam(required = false, name = "userId") Long userId) {
        return userPermissionAppService.userPermission(userId);
    }

    @Operation(summary = "获取平台用户列表")
    @GetMapping("/sys/list")
    public CommonResult<List<AdminUserResp>> querySysUserList() {
        List<AdminUserDto> list = userService.querySysUserList();
        if (CollectionUtils.isEmpty(list)) {
            return CommonResult.success(Collections.emptyList());
        }
        List<AdminUserResp> adminUserResps = UserDoToResp.INSTANCE.domainToRespList(list);
        return CommonResult.success(adminUserResps);
    }

}
